<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

class User extends BaseController
{
    // 登录接口
    public function login()
    {

    }

    /**
     * 获取部门负责人列表
     */
    public function getDepartmentLeaders()
    {
        // 查询所有是部门负责人的用户(is_leading=1)
        $leaders = Db::name('user')
            ->alias('u')
            ->join('user_department_relation udr', 'u.id = udr.user_id')
            ->join('user_department ud', 'udr.department_id = ud.id')
            ->where('udr.is_leading', 1)
            ->where('u.status', 1)
            ->field('u.id, u.username, u.realname')
            ->group('u.id')
            ->select();
        
        // 为每个负责人获取他们负责的部门名称
        foreach ($leaders as &$leader) {
            $departments = Db::name('user_department')
                ->alias('ud')
                ->join('user_department_relation udr', 'ud.id = udr.department_id')
                ->where('udr.user_id', $leader['id'])
                ->where('udr.is_leading', 1)
                ->column('ud.name');
            
            $leader['departments'] = implode('、', $departments);
        }
        
        return json($leaders);
    }
    
    /**
     * 获取用户列表
     */
    public function getUserList()
    {
        // 查询所有状态正常的用户
        $users = Db::name('user')
            ->where('status', 1)
            ->field('id, username, realname')
            ->select()
            ->toArray();
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $users
        ]);
    }
    
    /**
     * 获取当前用户所属部门信息
     */
    public function getUserDepartments()
    {
        // 获取当前用户ID，实际项目中应该从token或session中获取
        $userId = Request::param('userId', 0);
        
        // 如果没有提供userId，尝试从请求头获取token并解析
        if ($userId == 0) {
            $token = Request::header('Authorization');
            if ($token) {
                // 去掉Bearer前缀
                $token = str_replace('Bearer ', '', $token);
                try {
                    // 解析token获取用户信息
                    $userId = $this->getUserIdFromToken($token);
                } catch (\Exception $e) {
                    return json([
                        'code' => 401,
                        'msg' => '未授权或token已过期'
                    ]);
                }
            } else {
                return json([
                    'code' => 401,
                    'msg' => '未授权或token已过期'
                ]);
            }
        }
        
        // 查询用户所属部门
        $departments = Db::name('user_department')
            ->alias('ud')
            ->join('user_department_relation udr', 'ud.id = udr.department_id')
            ->where('udr.user_id', $userId)
            ->field('ud.id, ud.name, ud.code, udr.is_leading')
            ->select()
            ->toArray();
        
        // 处理部门信息
        $result = [];
        foreach ($departments as $dept) {
            $item = [
                'id' => $dept['id'],
                'name' => $dept['name'],
                'code' => $dept['code'],
                'is_leading' => $dept['is_leading']
            ];
            
            $result[] = $item;
        }
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $result
        ]);
    }
    
    /**
     * 从token中解析用户ID
     * @param string $token JWT令牌
     * @return int 用户ID
     */
    private function getUserIdFromToken($token)
    {
        // 这里应该根据您的实际token解析方式来实现
        // 示例使用JWT方式，实际项目中请替换为您的token解析逻辑
        try {
            // 如果使用Firebase JWT库
            // $decoded = \Firebase\JWT\JWT::decode($token, config('jwt.secret_key'), ['HS256']);
            // return $decoded->data->userId;
            
            // 简单示例，从请求中获取用户ID
            $userId = Request::param('test_user_id', 1);
            return $userId;
        } catch (\Exception $e) {
            throw new \Exception('Token解析失败');
        }
    }
}